<template>
  <el-dialog v-model="isShow" :title="data.data.name" width="1200" @close="close">
    <avue-crud
      :option="option"
      v-model:search="search"
      v-model:page="page"
      v-model="data.form"
      :table-loading="loading"
      :data="data.crud"
      :upload-before="uploadBefore"
      :permission="permissionList"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
    </avue-crud>
  </el-dialog>
</template>

<script>
import {
  createCourseware,
  getCoursewareLists,
  updateCourseware,
  deleteCourseware,
} from '@/api/position/knowledge';
import option from '@/option/position/coursewareLists';
import { mapGetters } from 'vuex';

const DOCTYPE = ['doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx', 'psd', 'jpg', 'jpeg', 'png', 'gif', 'bmp'];
const VIDEOTYPE = ['mp4', 'wav', 'rm', 'rmvb', 'flv', 'avi', 'wmv'];


export default {
  data() {
    return {
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option,
      isShow: false,
      file: null,
    };
  },
  props: {
    data: {
      type: Object,
    },
  },
  mounted() {
    this.option.column[1].dicData = this.website.coursewareType;
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    permissionList() {
      return {
        addBtn: true,
        viewBtn: true,
        delBtn: true,
        editBtn: true,
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    open() {
      this.data.form = {};
      this.data.crud = [];
      this.isShow = true;
      this.onLoad(this.page);
    },
    close() {
      this.data.form = {};
      this.data.crud = [];
      this.isShow = false;
    },
    handleImport(file) {
      const reader = new FileReader();
      reader.onload = e => {
        const data = e.target.result;
        this.data.form.file = data;
        this.$refs.file.value = '';
      };
      reader.readAsBinaryString(file.target.files[0]);
    },
    rowSave(row, done, loading) {
      const formdata = new FormData();
      formdata.append('knowledgeId', this.data.data.id);
      formdata.append('type', row.type);
      formdata.append('code', row.code);
      formdata.append('name', row.name);
      formdata.append('note', row.note);
      formdata.append('timeHour', row.timeHour);
      formdata.append('requireTimeHour', row.timeHour);
      if (this.file) {
        formdata.append('file', this.file);
      }
      createCourseware(formdata)
        .then(() => {
          this.$message.success('创建成功');
          this.onLoad(this.page);
          done();
        })
        .catch(err => {
          loading();
          this.$message.error('创建失败' + err);
        });
    },
    rowUpdate(row, index, done, loading) {
      const formdata = new FormData();
      formdata.append('knowledgeId', this.data.data.id);
      formdata.append('type', row.type);
      formdata.append('code', row.code);
      formdata.append('name', row.name);
      formdata.append('note', row.note);
      formdata.append('timeHour', row.timeHour);
      formdata.append('requireTimeHour', row.timeHour);
      formdata.append('id', row.id);
      if (this.file) {
        formdata.append('file', this.file);
      }
      updateCourseware(formdata)
        .then(() => {
          this.$message.success('修改成功');
          this.onLoad(this.page);
          done();
        })
        .catch(err => {
          loading();
          this.$message.error('修改失败' + err);
        });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return deleteCourseware(row.id, row.knowledgeId);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    uploadBefore(file, callback, loading) {
      loading();

      const index = file.name.lastIndexOf('.') + 1;
      const kzm = file.name.slice(index);
      const _kzm = kzm.toLocaleLowerCase()
      const { type } = this.data.form;
      if (!type) {
        this.$message.error('请先选择课件类型');
        return false;
      } else if (type == 'doc') {
        if (!DOCTYPE.includes(_kzm)) {
          this.$message.error('请上传' + DOCTYPE + '格式的文档');
          return false;
        }
      } else if (type == 'video') {
        if (!VIDEOTYPE.includes(_kzm)) {
          this.$message.error('请上传' + VIDEOTYPE + '格式的视频');
          return false;
        }
      }


      this.file = file;
      this.data.form.file = file.name;
      return true;
    },
    handleDelete() {
      // if (this.selectionList.length === 0) {
      //     this.$message.warning("请选择至少一条数据");
      //     return;
      // }
      // this.$confirm("确定将选择数据删除?", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning"
      // })
      //     .then(() => {
      //         return remove(this.ids);
      //     })
      //     .then(() => {
      //         this.onLoad(this.page);
      //         this.$message({
      //             type: "success",
      //             message: "操作成功!"
      //         });
      //         this.$refs.crud.toggleSelection();
      //     });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    onLoad(page) {
      this.loading = true;
      this.query['knowledgeId'] = this.data.data.id;
      getCoursewareLists(page.currentPage, page.pageSize, this.query).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data.crud = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.label {
  line-height: 30px;
}

.flex {
  display: flex;
}

.ml10 {
  margin-left: 10px;
}

.uploadBtn {
  position: relative;
}
</style>
